
module Ph

	#
	# Ph::Database
	#
	class Database

		attr_reader :elements, :name

		def initialize(name, &block)
			@elements    = Hash.new
			@name        = name
			@credentials = Hash.new
			instance_eval(&block)
		end
		
		# Sets Credentials for Mode 'mode'
		def credentials(mode, host, username, password)
			@credentials[mode] = [host, username, password]
		end
		
		# Sets Database Driver Class (not instance)
		def driver(driver)
			@driver = driver
		end

		def mode(m)
			@mode = m
		end
	
		# Alias for elements
		def [](name)
			@elements[name]
		end

		# TODO Fix Selection of Elements
		# Adds a constant to the class
		def add(*t)
			t.each do |k|
				@elements[k.name.to_sym] = k
			end			
		end
	
		# Adds a table to the database. (Shortcut)
		def table(name, &block)
			self.add Ph::Table.new(name, self, &block)
		end

		# Connects to the Database using the specified mode.
		def connect(mode=@mode)
			@mode = mode
			return @connection if @connection

			host, username, password = @credentials[mode]
			@connection = @driver.new(host, username, password)
		end

		#
		# Returns a Module containing Tables as Contant Names
		#
		def structure
			x = Module.new
			@elements.each do |k, v|
				x.const_set(k.capitalize, v)
			end

			return x
		end

	end

end
